package com.cn.shine.common.utils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtil {

	public static String FORMATSTR = "yyyy-MM-dd HH:mm:ss";

	/**
	 * 得到当前时间的格式化的字符串
	 * 
	 * @param sFormatStr
	 * @return
	 */
	public static String doGetDateOrTime(String sFormatStr) {
		return new SimpleDateFormat(sFormatStr).format(new Date());
	}

	/**
	 * 得到当前时间的格式化的字符串
	 * 
	 * @param sFormatStr
	 * @return
	 * @throws ParseException
	 */
	public static Date StringToDate(String sdate, String sFormatStr)
			throws ParseException {
		return new SimpleDateFormat(sFormatStr).parse(sdate);
	}

	/**
	 * 获得指定日期的前一天
	 * 
	 * @param specifiedDay
	 * @return
	 * @throws Exception
	 */
	public static Date getSpecifiedDayBefore(String specifiedDay) {// 可以用new
																	// Date().toLocalString()传递参数
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Calendar c = Calendar.getInstance();
		Date date = null;
		try {
			date = new SimpleDateFormat("yy-MM-dd").parse(specifiedDay);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		c.setTime(date);
		int day = c.get(Calendar.DATE);
		c.set(Calendar.DATE, day - 1);

		String dayBefore = df.format(c.getTime());
		try {
			date = df.parse(dayBefore);
		} catch (ParseException e) {
			// TODO
			e.printStackTrace();

		}
		return date;
	}

	/**
	 * 获得指定日期的后一天
	 * 
	 * @param specifiedDay
	 * @return
	 */
	public static String getSpecifiedDayAfter(String specifiedDay) {
		Calendar c = Calendar.getInstance();
		Date date = null;
		try {
			date = new SimpleDateFormat("yy-MM-dd").parse(specifiedDay);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		c.setTime(date);
		int day = c.get(Calendar.DATE);
		c.set(Calendar.DATE, day + 1);

		String dayAfter = new SimpleDateFormat("yyyy-MM-dd")
				.format(c.getTime());
		return dayAfter;
	}
	
	/**
	 * 获取月份
	 * @param dateStr 时间字符串 格式为yyyy-MM-dd
	 * @return
	 */
	public static int getMonthFromDate(String dateStr){
		Date date = null;
		try {
			date = new SimpleDateFormat("yyyy-MM-dd").parse(dateStr);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return date.getMonth()+1;
	}
	public static void main(String[] args){
		try {
			Date d1=DateUtil.StringToDate("2017-01-01 12:00:00","yyyy-MM-dd HH:mm:ss");
			Date d2=DateUtil.StringToDate("2017-01-01 12:00:01","yyyy-MM-dd HH:mm:ss");
			System.out.println(d2.getTime()-d1.getTime());
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
